<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        class Node {
            constructor(data) {
                this.prev = null;
                this.next = null;
                this.data = data;
            }
        }

        class CirularLinkedList {
            constructor() {
                this.head = null;
                this.count = 0;
                this.lowCount = 0;
            }

            push(data) {
                let node = new Node(data);
                let current = null;
                if (this.head == null) {
                    this.head = node;
                } else {
                    current = this.getNodeAt(this.size() - 1);
                    current.next = node;
                }

                node.next = this.head;
                this.count++;
            }

            insert(data, index) {
                if (index >= 0 && index <= this.count) {
                    let node = new Node(data);
                    if (index == 0) {
                        let current = this.head;
                        if (this.head == null) {
                            this.head = node;
                            node.next = this.head;
                        } else {
                            node.next = this.head;
                            // 注意一定要先获取到插入该元素之前的列表尾部，再进行将连接
                            current = this.getNodeAt(this.size() - 1);
                            this.head = node;
                            current.next = this.head;
                        }
                    } else {
                        let prev = this.getNodeAt(index - 1);
                        node.next = prev.next;
                        prev.next = node;
                    }
                    this.count++;
                    return true;
                }
            }

            remove(index) {
                if (index >= 0 && index < this.count){
                    let current = this.head;

                    this.count--;
                    return current.data;
                }
            }

            getNodeAt(n) {
                if (n < this.count) {
                    let current = this.head;
                    for (let i = 0; i < n; i++) {
                        current = current.next;
                    }
                    return current;
                }
            }

            size() {
                return this.count;
            }
        }

        let list = new CirularLinkedList();
    </script>
</body>

</html>